from flask import Flask, render_template, redirect, url_for, request, flash, session, jsonify, send_file
import json
import os
from datetime import datetime, timedelta
import random
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'your-secret-key-here'

# 用户数据存储路径
USER_DATA_FILE = 'users.json'

def load_users():
    try:
        with open(USER_DATA_FILE, 'rb') as f:
            raw = f.read()
            for encoding in ['utf-8-sig', 'utf-16', 'gbk']:
                try:
                    return json.loads(raw.decode(encoding))
                except UnicodeDecodeError:
                    continue
        # 所有编码尝试失败后重建文件
        with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump({}, f)
        return {}
    except json.JSONDecodeError:
        return {}

users = load_users()

# 生成模拟K线数据 - 完全替代pandas
class KLineGenerator:
    @staticmethod
    def generate(days=100, base_price=100):
        data = []
        base_date = datetime.now() - timedelta(days=days)
        
        for i in range(days):
            date = (base_date + timedelta(days=i)).strftime('%Y-%m-%d')
            open_price = round(base_price * random.uniform(0.9, 1.1), 2)
            close_price = round(base_price * random.uniform(0.9, 1.1), 2)
            high_price = round(max(open_price, close_price) * random.uniform(1.0, 1.1), 2)
            low_price = round(min(open_price, close_price) * random.uniform(0.9, 1.0), 2)
            
            data.append({
                'date': date,
                'open': open_price,
                'high': high_price,
                'low': low_price,
                'close': close_price
            })
        
        return data

# 数据导入导出 - 替代pandas
class DataHandler:
    @staticmethod
    def import_csv(file):
        data = []
        for line in file.stream:
            line = line.decode().strip()
            if not line or line.startswith('date'):
                continue
                
            parts = line.split(',')
            if len(parts) == 5:
                data.append({
                    'date': parts[0],
                    'open': float(parts[1]),
                    'high': float(parts[2]),
                    'low': float(parts[3]),
                    'close': float(parts[4])
                })
        return data
    
    @staticmethod
    def export_csv(data):
        csv = 'date,open,high,low,close\n'
        for item in data:
            csv += f"{item['date']},{item['open']},{item['high']},{item['low']},{item['close']}\n"
        return csv

# 修改后的路由
@app.route('/chart')
def chart():
    kline_data = KLineGenerator.generate()
    return render_template('chart.html', kline_data=kline_data)

@app.route('/api/export', methods=['POST'])
def export_data():
    data = request.json
    csv = DataHandler.export_csv(data)
    
    with open('temp_export.csv', 'w') as f:
        f.write(csv)
    
    return send_file('temp_export.csv', as_attachment=True)

@app.route('/data/import', methods=['POST'])
def import_data():
    if 'file' not in request.files:
        return jsonify({'error': 'No file uploaded'}), 400
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400
        
    data = DataHandler.import_csv(file)
    return jsonify({'data': data})

@app.route('/')
def index():
    if 'username' not in session:
        return redirect(url_for('login'))
        
    # 直接使用KLineGenerator.generate()替代未定义的generate_kline_data()
    kline_data = KLineGenerator.generate()
    return render_template('index.html', kline_data=kline_data)

@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users:
            flash('用户名已存在')
            return redirect(url_for('register'))
            
        users[username] = generate_password_hash(password)
        flash('注册成功，请登录')
        return redirect(url_for('login'))
        
    return render_template('register.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username not in users or not check_password_hash(users[username], password):
            flash('用户名或密码错误')
            return redirect(url_for('login'))
            
        session['username'] = username
        return redirect(url_for('index'))
        
    return render_template('login.html')

@app.route('/logout')
def logout():
    session.pop('username', None)
    return redirect(url_for('login'))

# 删除重复的/chart路由定义
# @app.route('/chart')  # 保留一个即可
# @app.route('/chart')  # 第154行

# 删除这些全局调用
# export_data()
# import_data()
def chart():
    kline_data = KLineGenerator.generate()
    return jsonify(kline_data)

@app.route('/practice')
def practice():
    scenario_data = {
        'scenario': '示例场景',
        'data': KLineGenerator.generate()  # 使用现有的K线生成器
    }
    return render_template('practice.html', scenario=scenario_data)

@app.route('/api/draw', methods=['POST'])
def draw():
    data = request.json
    # 保存用户绘制的图形
    return jsonify({'status': 'success'})

@app.route('/api/export', endpoint='export_api')
def export_data():
    # 实现实际的导出逻辑
    return "Data exported"

# 将两个import_data函数合并为一个，处理GET和POST请求
@app.route('/data/import', methods=['GET', 'POST'], endpoint='data_import')
def handle_data_import():
    if request.method == 'POST':
        if 'file' not in request.files:
            return jsonify({'error': 'No file uploaded'}), 400
        file = request.files['file']
        if file.filename == '':
            return jsonify({'error': 'No selected file'}), 400
        # 处理文件上传逻辑
        try:
            # 这里添加实际的文件处理代码
            return jsonify({'status': 'success', 'message': 'File uploaded successfully'})
        except Exception as e:
            return jsonify({'error': str(e)}), 500
    
    # GET请求处理逻辑
    return jsonify({'status': 'success', 'message': 'Import endpoint ready'})

# 用户进度存储
def save_user_progress(username, progress):
    progress_file = f'user_progress/{username}.json'
    with open(progress_file, 'w') as f:
        json.dump(progress, f)

@app.route('/progress', methods=['POST'])
def update_progress():
    if 'username' not in session:
        return redirect(url_for('login'))
    
    progress = request.json
    save_user_progress(session['username'], progress)
    return jsonify({'status': 'success'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)